package com.huiyin.ui;


import java.util.ArrayList;
import java.util.Calendar;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;
import com.huiyin.AppContext;
import com.huiyin.R;
import com.huiyin.UserInfo;
import com.huiyin.api.CustomResponseHandler;
import com.huiyin.api.RequstClient;
import com.huiyin.base.BaseActivity;
import com.huiyin.bean.LoginInfo;
import com.huiyin.bean.UpdataInfo;
import com.huiyin.ui.classic.CategoryFragmentNew;
import com.huiyin.ui.discuz.DiscuzBBSFragment;
import com.huiyin.ui.home.HomeFragment;
import com.huiyin.ui.moments.MomentsShowFragment;
import com.huiyin.ui.shoppingcar.ShoppingCarFragment;
import com.huiyin.ui.user.MyLeHuFragmentNew;
import com.huiyin.ui.web.HomeWebFragment;
import com.huiyin.utils.AppManager;
import com.huiyin.utils.DeviceUtils;
import com.huiyin.utils.JSONParseUtils;
import com.huiyin.utils.LogUtil;
import com.huiyin.utils.MathUtil;
import com.huiyin.utils.NetworkUtils;
import com.huiyin.utils.PreferenceUtil;
import com.huiyin.utils.SettingPreferenceUtil.SettingItem;
import com.huiyin.utils.StringUtils;
import com.huiyin.utils.UpdateManager;
import com.huiyin.utils.UpdateVersionTool;
import com.huiyin.utils.UpdateWebManager;
import com.huiyin.utils.Utils;
import com.huiyin.wight.BadgeView;
import com.jcvideoplayer.JCVideoPlayer;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

/***
 * 
 * @author xieshibin
 * 
 */
public class MainActivity extends BaseActivity {

	/** 快捷请求CODE */
	public final static int LNKTOOLS_REQUEST = 1;
	/** 快捷工具返回的RESULTCODE */
	public final static int LNKTOOLS_RESULT = 10;

	/**来自哪个界面**/
	public final static String From = "From";
	
	/**是否需要刷新秀场**/
	public final static String IS_REFRESH_MOMENTS = "isRefreshMoments";
	
//	private HomeFragment mHomeFragment;
	private HomeWebFragment mHomeWebFragment;
	//private CategoryFragment mClassicFragment;
	private CategoryFragmentNew mClassicFragment;
	private ShoppingCarFragment mShoppingCarFragment;
//	private HouseKeeperFragment mHouseKeeperFragment;
	//add by zhyao @2015/7/8  底部管家修改为论坛
	private DiscuzBBSFragment mDiscuzBBSFragment;
	//add by zhyao @2016/4/18  新增秀场
	private MomentsShowFragment mMomentsShowFragment;
	private MyLeHuFragmentNew mMyLeHuFragment;

	public static final String TAG = "MainActivity";
	private ArrayList<Fragment> mFragmentList;
	private FragmentManager mFragmentManager;
	public ViewPager mainPager;
	//add by zhyao @2015/8/27 添加DISCUZ_INDEX智慧社区入口
//	public static final int FIRST_PAGE_INDEX = 0, CLASSIC_INDEX = 1, SHOPPING_CAR_INDEX = 2, HOUSE_KEEPER_INDEX = 3, 
//			DISCUZ_INDEX = 4, MY_LEHU_INDEX = 5;
//	public static final int FIRST_PAGE_INDEX = 0, CLASSIC_INDEX = 1, SHOPPING_CAR_INDEX = 2, DISCUZ_INDEX = 3, MOMENTS_INDEX = 4, MY_LEHU_INDEX = 5;
	//delete by zhyao @2016/5/15 删除智慧社区
	public static final int FIRST_PAGE_INDEX = 0, CLASSIC_INDEX = 1, SHOPPING_CAR_INDEX = 2,  MOMENTS_INDEX = 3, MY_LEHU_INDEX = 4;
//	private TextView mFirstPageTV, mClassicTV, mShoppingCarTV, mHouseKeeperTV, mDiscuzTV, mMyLeHuTv;
//	private ImageView mFirstPageIV, mClassicIV, mShoppingCarIV, mHouseKeeperIV, mDiscuzIV, mMyLeHuIV;
//	private View mFirstPageView, mClassicView, mShoppingCarView, mHouseKeeperView, mDiscuzView, mMyLeHuView;
	private TextView mFirstPageTV, mClassicTV, mShoppingCarTV, mDiscuzTV, mMomentsTV, mMyLeHuTv;
	private ImageView mFirstPageIV, mClassicIV, mShoppingCarIV, mDiscuzIV, mMomentsIV, mMyLeHuIV;
	private View mFirstPageView, mClassicView, mShoppingCarView, mDiscuzView, mMomentsView, mMyLeHuView;

//	private ImageView mFirstPageFlag, mClassicFlag, mShoppingCarFlag, mHouseKeeperFlag, mDiscuzFlag, mMyLeHuFlag;
	private ImageView mFirstPageFlag, mClassicFlag, mShoppingCarFlag, mDiscuzFlag, mMomentsFlag, mMyLeHuFlag;
	
	private SettingItem mSettingItem;

	private BadgeView shoppingBadge, messageBadge;

	// private LoginReceiver mLoginReceiver;

	/**来自哪个界面(上一个Activity是谁)**/
	private String from;
	
	/**是否需要刷新秀场**/
	private boolean isRefreshMoments;
	
	/**
	 * 升级类型： 1.android升级   4.html5升级
	 */
	private String updateType = "1";
	
	private ImageView mHudImg;
	
	private DisplayImageOptions options;
	
	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		if(intent.hasExtra(From)){
			from = intent.getStringExtra(From);
			if(null != from && from.equals("login")){
				//来自登录
				int currentIndex = mainPager.getCurrentItem();
				if(currentIndex == MY_LEHU_INDEX){
					
					//设置通知是否加载用户信息(当登录回到乐虎界面，不主动去加载UserInfo-目的不为别的，只为节省流量，和不影响其他http请求)
					mMyLeHuFragment.setLoadUserInfo(false);
				}
			}
		}
		if(intent.hasExtra(IS_REFRESH_MOMENTS)) {
			isRefreshMoments = intent.getBooleanExtra(IS_REFRESH_MOMENTS, false);
		}
		Log.i("helloword", "MainActivity onNewIntent");
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		LogUtil.i("Device", "width:"+DeviceUtils.getWidthMaxDp(this));
		initView();
		autoLogin();

		new ProgressDialog(this);
		if (!NetworkUtils.isNetworkAvailable(this)) {
			Toast.makeText(this, "网络故障，请先检查网络连接!", Toast.LENGTH_LONG).show();
			return;
		} else {
			// 检测版本
			requestVersion();
		}

		// 百度云推送
		mSettingItem = AppContext.getInstance().getSettingSharePreference();
		if (mSettingItem.isMessage()) {
			PushManager.startWork(this, PushConstants.LOGIN_TYPE_API_KEY, Utils.getMetaValue(this, "api_key"));
			if (mSettingItem.isMessageTime()) {
                PushManager.setNoDisturbMode(this, 23, 0, 6, 50);
            } else {
                PushManager.setNoDisturbMode(this, 0, 0, 0, 0);
            }
            AppContext.getInstance().setBaiduNotification((mSettingItem.isMessageSound()));

		}

		// mLoginReceiver = new LoginReceiver();
		// IntentFilter filter = new IntentFilter();
		// filter.addAction("com.login.success");
		// filter.addAction("com.login.exit");
		// registerReceiver(mLoginReceiver, filter);

		LogUtil.i("UserInfo", "MainActivity OnCreate is Null" + (null == AppContext.userId));
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		JCVideoPlayer.releaseAllVideos();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// unregisterReceiver(mLoginReceiver);
	}

	private void initBottomView() {
		BottomItemOnClickListener mClickListener = new BottomItemOnClickListener();
	
		mClassicView = findViewById(R.id.classic_item);
		mClassicIV = (ImageView) findViewById(R.id.classic_iv);
		mClassicTV = (TextView) findViewById(R.id.classic_tv);

		mShoppingCarView = findViewById(R.id.shopping_car_item);
		mShoppingCarIV = (ImageView) findViewById(R.id.shopping_car_iv);
		mShoppingCarTV = (TextView) findViewById(R.id.shopping_car_tv);

		mFirstPageView = findViewById(R.id.first_page_item);
		mFirstPageIV = (ImageView) findViewById(R.id.first_page_iv);
		mFirstPageTV = (TextView) findViewById(R.id.first_page_tv);

		
//		mHouseKeeperView = findViewById(R.id.house_keeper_item);
//		mHouseKeeperIV = (ImageView) findViewById(R.id.house_keeper_iv);
//		mHouseKeeperTV = (TextView) findViewById(R.id.house_keeper_tv);
		
		// add by zhyao @2015/8/27 添加智慧社区
		mDiscuzView = findViewById(R.id.discuz_item);
		mDiscuzIV = (ImageView) findViewById(R.id.discuz_iv);
		mDiscuzTV = (TextView) findViewById(R.id.discuz_tv);
		
		// add by zhyao @2016/4/18 添加秀场
		mMomentsView = findViewById(R.id.moments_item);
		mMomentsIV = (ImageView) findViewById(R.id.moments_iv);
		mMomentsTV = (TextView) findViewById(R.id.moments_tv);

		mMyLeHuView = findViewById(R.id.my_lehu_item);
		mMyLeHuIV = (ImageView) findViewById(R.id.my_lehu_iv);
		mMyLeHuTv = (TextView) findViewById(R.id.my_lehu_tv);

		mFirstPageFlag = (ImageView) findViewById(R.id.first_page_item_flag);
		mClassicFlag = (ImageView) findViewById(R.id.classic_item_flag);
		mShoppingCarFlag = (ImageView) findViewById(R.id.shopping_car_item_flag);
//		mHouseKeeperFlag = (ImageView) findViewById(R.id.house_keeper_item_flag);
		mDiscuzFlag = (ImageView) findViewById(R.id.discuz_item_flag);
		mMomentsFlag = (ImageView) findViewById(R.id.moments_item_flag);
		mMyLeHuFlag = (ImageView) findViewById(R.id.my_lehu_item_flag);

		
		mClassicView.setOnClickListener(mClickListener);
		mShoppingCarView.setOnClickListener(mClickListener);
		mFirstPageView.setOnClickListener(mClickListener);
//		mHouseKeeperView.setOnClickListener(mClickListener);
		mDiscuzView.setOnClickListener(mClickListener);
		mMomentsView.setOnClickListener(mClickListener);
		mMyLeHuView.setOnClickListener(mClickListener);

	}

	@Override
	protected void onResume() {
		super.onResume();

		if (AppContext.getInstance().mUserInfo == null) {
			setTheShoppcar(0);
			setTheMessage(0);
		} else {
			setTheShoppcar(AppContext.getInstance().mUserInfo.getShoppingCart());
			int count = MathUtil.stringToInt(AppContext.getInstance().mUserInfo.systemMessage);
			setTheMessage(count);
		}

		if (AppContext.MAIN_TASK == null || StringUtils.isEmpty(AppContext.MAIN_TASK)) {
			return;
		}
		if (AppContext.MAIN_TASK.equals(AppContext.FIRST_PAGE)) {
			mainPager.setCurrentItem(FIRST_PAGE_INDEX);
			updataBottomStatu(FIRST_PAGE_INDEX);
		} else if (AppContext.MAIN_TASK.equals(AppContext.CLASSIC)) {
			mainPager.setCurrentItem(CLASSIC_INDEX);
			updataBottomStatu(CLASSIC_INDEX);
		} else if (AppContext.MAIN_TASK.equals(AppContext.SHOPCAR)) {
			mainPager.setCurrentItem(SHOPPING_CAR_INDEX);
			updataBottomStatu(SHOPPING_CAR_INDEX);
//		} else if (AppContext.MAIN_TASK.equals(AppContext.HOUSEKEEPER)) {
//			mainPager.setCurrentItem(HOUSE_KEEPER_INDEX);
//			updataBottomStatu(HOUSE_KEEPER_INDEX);
		} 
//		else if (AppContext.MAIN_TASK.equals(AppContext.DISCUZ)) {
//			mainPager.setCurrentItem(DISCUZ_INDEX);
//			updataBottomStatu(DISCUZ_INDEX);
//		}
		else if (AppContext.MAIN_TASK.equals(AppContext.MOMENTS)) {
			mainPager.setCurrentItem(MOMENTS_INDEX);
			updataBottomStatu(MOMENTS_INDEX);
			//发布新的秀图、秀好物和秀视频之后，刷新秀场首页
			if(mMomentsShowFragment != null && isRefreshMoments) {
				mMomentsShowFragment.onRefreshData();
				isRefreshMoments = false;
			}
			
		} else if (AppContext.MAIN_TASK.equals(AppContext.LEHU)) {
			mainPager.setCurrentItem(MY_LEHU_INDEX);
			updataBottomStatu(MY_LEHU_INDEX);
		}

	}

	private void setFirstPage(boolean isSelect) {
		mFirstPageView.setSelected(isSelect);
		mFirstPageIV.setSelected(isSelect);
		mFirstPageTV.setSelected(isSelect);
		mFirstPageFlag.setSelected(isSelect);
	}

	private void setClassic(boolean isSelect) {
		mClassicView.setSelected(isSelect);
		mClassicIV.setSelected(isSelect);
		mClassicTV.setSelected(isSelect);
		mClassicFlag.setSelected(isSelect);
	}

	private void setShoppingCar(boolean isSelect) {
		mShoppingCarView.setSelected(isSelect);
		mShoppingCarIV.setSelected(isSelect);
		mShoppingCarTV.setSelected(isSelect);
		mShoppingCarFlag.setSelected(isSelect);
	}

//	private void setKeeperHouse(boolean isSelect) {
//		mHouseKeeperView.setSelected(isSelect);
//		mHouseKeeperIV.setSelected(isSelect);
//		mHouseKeeperTV.setSelected(isSelect);
//		mHouseKeeperFlag.setSelected(isSelect);
//	}
	
	// add by zhyao @2015/8/27 设置智慧社区状态
	private void setDiscuz(boolean isSelect) {
		mDiscuzView.setSelected(isSelect);
		mDiscuzIV.setSelected(isSelect);
		mDiscuzTV.setSelected(isSelect);
		mDiscuzFlag.setSelected(isSelect);
	}
	
	// add by zhyao @2016/4/18 设置秀场状态
	private void setMoments(boolean isSelect) {
		mMomentsView.setSelected(isSelect);
		mMomentsIV.setSelected(isSelect);
		mMomentsTV.setSelected(isSelect);
		mMomentsFlag.setSelected(isSelect);
	}

	private void setMyLeHu(boolean isSelect) {
		mMyLeHuView.setSelected(isSelect);
		mMyLeHuIV.setSelected(isSelect);
		mMyLeHuTv.setSelected(isSelect);
		mMyLeHuFlag.setSelected(isSelect);
	}

	private void updataBottomStatu(int index) {
		switch (index) {
		case FIRST_PAGE_INDEX: {
			/* 首页 */
			if (!mFirstPageView.isSelected()) {
				setTitle(R.string.first_page);
				setFirstPage(true);
				setClassic(false);
				setShoppingCar(false);
//				setKeeperHouse(false);
				setDiscuz(false);
				setMoments(false);
				setMyLeHu(false);
				//mClassicFragment.backToCategory();
			}

		}
			break;
		case CLASSIC_INDEX: {
			/* 分类 */
			if (!mClassicView.isSelected()) {
				setTitle(R.string.classification);
				setFirstPage(false);
				setClassic(true);
				setShoppingCar(false);
//				setKeeperHouse(false);
				setDiscuz(false);
				setMoments(false);
				setMyLeHu(false);
				//mClassicFragment.backToCategory();
				//mClassicFragment.backToOrigin();
			}
		}
			break;
		case SHOPPING_CAR_INDEX: {
			/* 购物车 */
			if (!mShoppingCarView.isSelected()) {
				setTitle(R.string.shopping_car);
				setFirstPage(false);
				setClassic(false);
				setShoppingCar(true);
//				setKeeperHouse(false);
				setDiscuz(false);
				setMoments(false);
				setMyLeHu(false);
				//mClassicFragment.backToCategory();
			}
		}
			break;
//		case HOUSE_KEEPER_INDEX: {
//			/* 管家 */
//			if (!mHouseKeeperView.isSelected()) {
//				setTitle(R.string.housekeeper);
//				setFirstPage(false);
//				setClassic(false);
//				setShoppingCar(false);
//				setKeeperHouse(true);
//				setDiscuz(false);
//				setMyLeHu(false);
//				mClassicFragment.backToCategory();
//			}
//		}
//			break;
//		case DISCUZ_INDEX: {
//			/* 智慧社区*/
//			if (!mDiscuzView.isSelected()) {
//				setTitle(R.string.discuz);
//				setFirstPage(false);
//				setClassic(false);
//				setShoppingCar(false);
////				setKeeperHouse(false);
//				setDiscuz(true);
//				setMoments(false);
//				setMyLeHu(false);
//				//mClassicFragment.backToCategory();
//			}
//		}
//			break;
		case MOMENTS_INDEX: {
			/* 秀场 */
			if (!mMomentsView.isSelected()) {
				setTitle(R.string.moments);
				setFirstPage(false);
				setClassic(false);
				setShoppingCar(false);
//				setKeeperHouse(false);
				setDiscuz(false);
				setMoments(true);
				setMyLeHu(false);
				//mClassicFragment.backToCategory();
			}
		}
			break;
		case MY_LEHU_INDEX: {
			/* 我的乐虎 */
			if (!mMyLeHuView.isSelected()) {
				setTitle(R.string.my_lehu);
				setFirstPage(false);
				setClassic(false);
				setShoppingCar(false);
//				setKeeperHouse(false);
				setDiscuz(false);
				setMoments(false);
				setMyLeHu(true);
				//mClassicFragment.backToCategory();
			}
		}
			break;
		}

	}
	
	private String oldUserId = AppContext.userId;
	protected class BottomItemOnClickListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.first_page_item: {
				Log.d(TAG, "BottomItemOnClickListener : FIRST_PAGE_INDEX");
				AppContext.MAIN_TASK = AppContext.FIRST_PAGE;
				mainPager.setCurrentItem(FIRST_PAGE_INDEX);
				updataBottomStatu(FIRST_PAGE_INDEX);
			}
				break;
			case R.id.classic_item: {
				Log.d(TAG, "BottomItemOnClickListener : CLASSIC");
				AppContext.MAIN_TASK = AppContext.CLASSIC;
				mainPager.setCurrentItem(CLASSIC_INDEX);
				updataBottomStatu(CLASSIC_INDEX);
			}
				break;
			case R.id.shopping_car_item: {
				Log.d(TAG, "BottomItemOnClickListener : SHOPCAR");
				//add by zhyao @2016/7/6 未登录情况下先登录
				if(!appIsLogin(true)) return;
				
				if (AppContext.MAIN_TASK != AppContext.SHOPCAR) {
					AppContext.MAIN_TASK = AppContext.SHOPCAR;
					mainPager.setCurrentItem(SHOPPING_CAR_INDEX);
					updataBottomStatu(SHOPPING_CAR_INDEX);
					// setTheShoppcar(0);
					mShoppingCarFragment.pageSelected(SHOPPING_CAR_INDEX);
				}
			}
				break;
//			case R.id.house_keeper_item: {
//				AppContext.MAIN_TASK = AppContext.HOUSEKEEPER;
//				mainPager.setCurrentItem(HOUSE_KEEPER_INDEX);
//				updataBottomStatu(HOUSE_KEEPER_INDEX);
//			}
//				break;
				// add by zhyao @2015/8/27 添加智慧社区（论坛）
//			case R.id.discuz_item: {
//				Log.d(TAG, "BottomItemOnClickListener : DISCUZ");
//				if (AppContext.userId == null) {
//					// 判断登录
//					Intent intent = new Intent(MainActivity.this,
//							LoginActivity.class);
//					startActivity(intent);
//				}
//				else {
//					AppContext.MAIN_TASK = AppContext.DISCUZ;
//					mainPager.setCurrentItem(DISCUZ_INDEX);
//					updataBottomStatu(DISCUZ_INDEX);
//					
//					Log.d(TAG, "oldUserId = " + oldUserId + "  newUserId = " + AppContext.userId);
//					if(!AppContext.userId.equals(oldUserId)) {
//						oldUserId = AppContext.userId;
//						mDiscuzBBSFragment.loadUrl();
//					}
//					
//				}
//				
//			}
//				break;
			// add by zhyao @2016/4/18 添加秀场
			case R.id.moments_item: {
				Log.d(TAG, "BottomItemOnClickListener : MOMENTS");
				AppContext.MAIN_TASK = AppContext.MOMENTS;
				mainPager.setCurrentItem(MOMENTS_INDEX);
				updataBottomStatu(MOMENTS_INDEX);
				
			}
				break;
			case R.id.my_lehu_item: {
				Log.d(TAG, "BottomItemOnClickListener : LEHU");
				if (AppContext.MAIN_TASK != AppContext.LEHU) {
					AppContext.MAIN_TASK = AppContext.LEHU;
					mainPager.setCurrentItem(MY_LEHU_INDEX);
					updataBottomStatu(MY_LEHU_INDEX);
					// setTheMessage(0);
					mMyLeHuFragment.pageSelected(MY_LEHU_INDEX);
				}
			}
				break;
			}
		}

	}

	/**
	 * 隐式登录
	 * @param userName
	 * @param psw
	 */
	private void doLogin(String userName, String psw) {

		LogUtil.i("UserInfo", "MainActivity 自动登录");
		
		RequstClient.loginOverLoad(userName, psw, "", "-1", new CustomResponseHandler(this) {
			@Override
			public void onSuccess(int statusCode, Header[] headers, String content) {
				super.onSuccess(statusCode, headers, content);
				
				//异常消息显示
				if(JSONParseUtils.isErrorJSONResult(content)){
					String msg = JSONParseUtils.getString(content, "msg");
					showMyToast(msg);
					return;
				}
				
				//解析用户信息
				String userJson = JSONParseUtils.getJSONObject(content, "user");
				UserInfo mUserInfo = UserInfo.explainJson(userJson, mContext);
				AppContext.mUserInfo = mUserInfo;
				AppContext.userId = mUserInfo.userId;
				
				//添加登录日志
				addUserLoginLog(AppContext.userId);
				
				setTheShoppcar(mUserInfo.getShoppingCart());
				setTheMessage(Integer.valueOf(mUserInfo.systemMessage));

				LogUtil.i("UserInfo", "MainActivity doLogin is Null" + (null == AppContext.userId));
			}

		});
	}
	
	/**
	 * 添加登录日志
	 */
	private void addUserLoginLog(String userId) {
		
		// 添加登录日志
		RequstClient.addUserLoginLog(userId, AppContext.getShopcardId(), new CustomResponseHandler(this, false) {
			@Override
			public void onSuccess(int statusCode, Header[] headers, String content) {
				super.onSuccess(statusCode, headers, content);

				// 异常消息显示
				if (JSONParseUtils.isErrorJSONResult(content)) {
					String msg = JSONParseUtils.getString(content, "msg");
					LogUtil.i("MainActivity", "添加登录日志---"+msg);
					return;
				}

				//删除本地购物车ID，清空本地购物车
				AppContext.deleteShopcardId();
				
				// 添加登录日志
				LogUtil.i("MainActivity", "添加登录日志---成功");
			}

		});
	}
	
	/***
	 * 自动登录
	 */
	private void autoLogin() {
		LoginInfo mLoginInfo = AppContext.getLoginInfo(getApplicationContext());
		if (mLoginInfo.isChecked && !StringUtils.isEmpty(mLoginInfo.userName) && !StringUtils.isEmpty(mLoginInfo.psw)) {
			doLogin(mLoginInfo.userName, mLoginInfo.psw);
		}
	}

	private void initView() {
		AppManager.getAppManager().addActivity(this);

		initBottomView();

		mFragmentManager = getSupportFragmentManager();
		mFragmentList = new ArrayList<Fragment>();
//		mClassicFragment = new CategoryFragment();
		mClassicFragment = new CategoryFragmentNew();
		mShoppingCarFragment = new ShoppingCarFragment();
//		mHouseKeeperFragment = new HouseKeeperFragment();
		//add by zhyao @2015/7/8  底部管家修改为论坛
		mDiscuzBBSFragment = new DiscuzBBSFragment();
		mMomentsShowFragment = new MomentsShowFragment();
		mMyLeHuFragment = new MyLeHuFragmentNew();

		//mHomeFragment = new HomeFragment();
		mHomeWebFragment = new HomeWebFragment();
		
//		mFragmentList.add(mHomeFragment);
		mFragmentList.add(mHomeWebFragment);
		mFragmentList.add(mClassicFragment);
		mFragmentList.add(mShoppingCarFragment);
//		mFragmentList.add(mHouseKeeperFragment);
		//add by zhyao @2015/7/8  底部管家修改为论坛
		//mFragmentList.add(mDiscuzBBSFragment);
		mFragmentList.add(mMomentsShowFragment);
		mFragmentList.add(mMyLeHuFragment);
		mainPager = (ViewPager) findViewById(R.id.content_pager);
		mainPager.setOffscreenPageLimit(5);
		mainPager.setAdapter(new MainPagerAdapter(mFragmentManager));
		mainPager.setOnPageChangeListener(new OnPageChangeListener() {
			@Override
			public void onPageSelected(int position) {
				updataBottomStatu(position);
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
			}
		});
		mainPager.setCurrentItem(0);
		updataBottomStatu(FIRST_PAGE_INDEX);
		
		options = new DisplayImageOptions.Builder().showStubImage(-1)
				.showImageForEmptyUri(R.drawable.image_default_rectangle).showImageOnFail(R.drawable.image_default_rectangle)
				.imageScaleType(ImageScaleType.IN_SAMPLE_INT).cacheInMemory(true).cacheOnDisc(true)
				.bitmapConfig(Bitmap.Config.RGB_565).build();
		
		//delete by zhyao @2016/7/4 删除遮罩(新的Html5首页)
		//首次进入展示遮罩引导页
//		boolean isFirstStart = PreferenceUtil.getInstance(getApplicationContext()).isFirstStart();
//		if(isFirstStart) {
//			mHudImg = (ImageView) findViewById(R.id.img_hud);
//			mHudImg.setVisibility(View.VISIBLE);
//			//mHudImg.setBackgroundResource(hudIds[hudIndex]);
//		    ImageLoader.getInstance().displayImage("drawable://" + hudIds[hudIndex], mHudImg, options);
//			mHudImg.setOnClickListener(new HudClickListener());
//			hudHandler.sendEmptyMessageDelayed(SHOW_NEXT_HUD, SHOW_NEXT_HUD_TIEM);
//			
//			
//		}
		//add by zhyao @2016/7/4 删除遮罩(新的Html5首页),设置是否 第一次进入为否
		PreferenceUtil.getInstance(getApplicationContext()).setFirstStart(false);
		
	}
	
	private int[] hudIds = {R.drawable.hud_01};
	private int hudIndex = 0;
	private static int SHOW_NEXT_HUD = 0;
	private static int SHOW_NEXT_HUD_TIEM = 5 * 1000;
	
	class HudClickListener implements OnClickListener {

		public static final int MIN_CLICK_DELAY_TIME = 2000;
        private long lastClickTime = 0;
        
		@Override
		public void onClick(View v) {
			long currentTime = Calendar.getInstance().getTimeInMillis();
            if (currentTime - lastClickTime > MIN_CLICK_DELAY_TIME) {
                lastClickTime = currentTime;
    			showNextHud();
            } 
			
		}
		
	}
	
	Handler hudHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if(msg.what == SHOW_NEXT_HUD) {
				showNextHud();
			}
		};
	};
	/**
	 * 显示下一站遮罩图，没有则隐藏
	 */
	private void showNextHud() {
		hudIndex++;
		if(hudIndex < hudIds.length) {
			//mHudImg.setBackgroundResource(hudIds[hudIndex]);
			ImageLoader.getInstance().displayImage("drawable://" + hudIds[hudIndex], mHudImg, options);
		}
		else {
			mHudImg.setVisibility(View.GONE);
			PreferenceUtil.getInstance(getApplicationContext()).setFirstStart(false);
			hudHandler.removeMessages(SHOW_NEXT_HUD);
			return;
		}
		hudHandler.removeMessages(SHOW_NEXT_HUD);
		hudHandler.sendEmptyMessageDelayed(SHOW_NEXT_HUD, SHOW_NEXT_HUD_TIEM);
	}

	private long secondTime = 0;

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		long spaceTime = 0;
		long firstTime = 0;
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (mainPager.getCurrentItem() != 0) {
				goShopping(null);
				return false;
			}
			firstTime = System.currentTimeMillis();
			spaceTime = firstTime - secondTime;
			secondTime = firstTime;
			if (spaceTime > 2000) {
				Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
				return false;
			} else {
				AppManager.getAppManager().AppExit(this);
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	class MainPagerAdapter extends FragmentStatePagerAdapter {

		public MainPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int arg0) {
			return mFragmentList.get(arg0);
		}

		@Override
		public int getCount() {
			return mFragmentList == null ? 0 : mFragmentList.size();
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
		}
	}

	/***
	 * 检测版本
	 * */
	private void requestVersion() {
		CustomResponseHandler handler = new CustomResponseHandler(this, false) {
			@Override
			public void onRefreshData(String content) {
				analyticalVersionData(content);
			}
		};
		// add by zhyao @2015/8/25 APK更新
		RequstClient.getVersion(updateType, handler);
	}

	/***
	 * 解析数据
	 * */
	private void analyticalVersionData(String content) {
		try {
			JSONObject roots = new JSONObject(content);
			if (roots.getString("type").equals("1")) {
				String url = roots.getString("editionUrl");
				String versionName = roots.getString("editionName");
				String versionVersion = roots.getString("editionExplain");

				int versionCode = Integer.valueOf(roots.getString("edition"));
				UpdataInfo updateInfo = new UpdataInfo();
				updateInfo.setUrl(url);
				updateInfo.setVersion(versionName);
				updateInfo.setVersionCode(versionCode);
				updateInfo.setDescription(versionVersion);
				
				if("1".equals(updateType)) {
					updateApk(updateInfo);
				}
				else if("4".equals(updateType)) {
					updaeHtml(updateInfo);
				}

			} else {
				return;
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}

	}

	private void updateApk(final UpdataInfo updateInfo) {
		if (UpdateVersionTool.getVersionCode(this) >= updateInfo.getVersionCode()) {
			updateType = "4";
			requestVersion();
			return;
		} else {
			UpdateManager manager = new UpdateManager(this, "huiyin", updateInfo.getUrl());
			manager.checkUpdate(updateInfo.getVersionCode(), updateInfo.getDescription());
		}
	}
	
	private void updaeHtml(final UpdataInfo updateInfo) {
		UpdateWebManager manager = new UpdateWebManager(MainActivity.this, "huiyin_html.zip", updateInfo.getUrl());
		manager.checkUpdate(updateInfo.getVersionCode(), updateInfo.getDescription());
	}

	public void goShopping(View v) {
		AppContext.MAIN_TASK = AppContext.FIRST_PAGE;
		mainPager.setCurrentItem(FIRST_PAGE_INDEX);
		updataBottomStatu(FIRST_PAGE_INDEX);
	}

	public void setTheShoppcar(int count) {

		if (shoppingBadge == null) {
			shoppingBadge = new BadgeView(this, mShoppingCarView);
		}
		if (count <= 0) {
			shoppingBadge.hide();
		} else if (count <= 99) {
			shoppingBadge.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);
			shoppingBadge.setTextSize(12);
			shoppingBadge.setText(String.valueOf(count));
			shoppingBadge.show();
		} else if (count > 99) {
			shoppingBadge.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);
			shoppingBadge.setTextSize(12);
			shoppingBadge.setText("99+");
			shoppingBadge.show();
		}
	}

	public void setTheMessage(int count) {

		if (messageBadge == null) {
			messageBadge = new BadgeView(this, mMyLeHuView);
		}
		if (count <= 0) {
			messageBadge.hide();
		} else if (count <= 99) {
			messageBadge.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);
			messageBadge.setTextSize(12);
			messageBadge.setText(String.valueOf(count));
			messageBadge.show();
		} else if (count > 99) {
			messageBadge.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);
			messageBadge.setTextSize(12);
			messageBadge.setText("99+");
			messageBadge.show();
		}
	}

	// 登陆成功以及注销登陆的广播接收器
	public class LoginReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals("com.login.success")) {
				int shoppcar = intent.getIntExtra("shoppcar", 0);
				setTheShoppcar(shoppcar);
				int message = intent.getIntExtra("message", 0);
				setTheMessage(message);
			}
			if (action.equals("com.login.exit")) {
				setTheShoppcar(0);
				setTheMessage(0);
			}
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		
	    if(mDiscuzBBSFragment != null) {
	    	mDiscuzBBSFragment.onActivityResult(requestCode, resultCode, data);
	    }
	}
	
	
}
